import React, { Component } from 'react';
import ipfsClient from 'ipfs-http-client';
// import './App.css';

let ipfs = ipfsClient('localhost', '5002', { protocol: 'http' });

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: '',
      hash: '',
      content: ''
    };
  }

  // () => 剪头函数就不用在constructor函数中进行绑定了
  handleClick() {
    console.log(this.state.text);
    this.saveTextToIpfs(this.state.text);
  }

  saveTextToIpfs(text) {
    const descBuf = Buffer.from(text, 'utf-8');
    ipfs.add(descBuf).then((res) => {
      console.log(res[0].hash);
      this.setState({
        hash: res[0].hash
      })
    })
  }

  handleReadClick() {
    ipfs.cat(this.state.hash).then((res) => {
      // console.log(res);
      // res返回的是Uint8Array对象，用自带的TextDecoder对象转换成可识别的utf-8对象
      let content = new TextDecoder('utf-8').decode(res);
      this.setState({
        content: content
      });
    });
  }

  render() {
    return (
      <div className="App">
        <input value={this.state.text} type="text" onChange={(e)=>{
          this.setState({
            text: e.target.value
          })
        }} />
        <button onClick={() => this.handleClick()}>提交到IPFS</button>
        <p>
          hash is: {this.state.hash}
        </p>
        <hr />
        <button onClick={() => this.handleReadClick()}>从IPFS读取数据</button>
        <p>
          {this.state.content}
        </p>
      </div>
      
    );
  }
}

export default App;
